﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YunSpace.Core;

namespace YunSpace.ThirdService
{
    /// <summary>
    /// 容联.云通讯
    /// http://www.yuntongxun.com/doc/rest/restabout/3_1_1_1.html
    /// </summary>
    public class RongLianSmsManger
    {
        #region 属性
        public string BaseUrl
        {
            get
            {
                return Configs.GetValue("RONGLIAN_SMS_BASE_URL");
            }
        }

        public string TemplateId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_SMS_TEMPLATE_ID");
            }
        }

        public string RandomPasswordTemplateId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_RANDOM_LOGIN_TEMPLATE_ID");
            }
        }

        /// <summary>
        /// 场地订单模板
        /// </summary>
        public string SiteOrderTemplateId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_SITEORDER_TEMPLATE_ID");
            }
        }

        /// <summary>
        /// 场地推荐模板
        /// </summary>
        public string SiteFlowTemplateId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_SITEFLOW_TEMPLATE_ID");
            }
        }

        /// <summary>
        /// 订单指派模板
        /// </summary>
        public string GiveOrderTemplateId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_GIVEORDER_TEMPLATE_ID");
            }
        }

        /// <summary>
        /// 申请审核模板
        /// </summary>
        public string ApplyTemplateId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_APPLY_TEMPLATE_ID");
            }
        }

        /// <summary>
        /// 审核回复模板
        /// </summary>
        public string AuditingTemplateId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_AUDITING_TEMPLATE_ID");
            }
        }

        /// <summary>
        /// 小程序模板
        /// </summary>
        public string WeChatTemplateId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_WECHAT_TEMPLATE_ID");
            }
        }

        /// <summary>
        /// 需求单超期提醒
        /// </summary>
        public string CheckOrderTemplateId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_CHECKORDER_ID");
            }
        }

        public string AccountId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_SMS_ACCOUNTS_ID");
            }
        }

        public string Token
        {
            get
            {
                return Configs.GetValue("RONGLIAN_SMS_AUTH_TOKEN");
            }
        }

        public string AppId
        {
            get
            {
                return Configs.GetValue("RONGLIAN_SMS_APPID");
            }
        }
        public string Message
        {
            get
            {
                return Configs.GetValue("RONGLIAN_SMS_ALERT_MESSAGE");
            }
        }


        public string Timestamp
        {
            get
            {
                return DateTime.Now.ToString("yyyyMMddHHmmss");
            }
        }

        public string Code
        {
            get
            {
                return Configs.GetValue("RONGLIAN_CODE");
            }
        }
        
        public string RegisterCode
        {
            get
            {
                return Configs.GetValue("RONGLIAN_REGISTER_CODE");
            }
        }
        //public string GetAuthorization(string timestamp) {
        //    var result = string.Format("{0}:{1}", this.AccountId, timestamp);
        //    byte[] byteArray = System.Text.Encoding.Default.GetBytes(result);

        //    return Convert.ToBase64String(byteArray);
        //}

        //public string GetSign(string timestamp) {
        //    var result = string.Format("{0}{1}{2}", this.AccountId, this.Token, timestamp);
        //    var encrypt = new HashEncrypt();

        //    return encrypt.MD5Encrypt(result);
        //} 
        #endregion

        #region 私有方法
        private string getDictionaryData(Dictionary<string, object> data)
        {
            string ret = null;
            foreach (KeyValuePair<string, object> item in data)
            {
                if (item.Value != null && item.Value.GetType() == typeof(Dictionary<string, object>))
                {
                    ret += item.Key.ToString() + "={";
                    ret += getDictionaryData((Dictionary<string, object>)item.Value);
                    ret += "};";
                }
                else
                {
                    ret += item.Key.ToString() + "=" + (item.Value == null ? "null" : item.Value.ToString()) + ";";
                }
            }
            return ret;
        }

        private string Send(string phone, string tempateId, string[] data)
        {
            //var timestamp = this.Timestamp;
            //var authorization = this.GetAuthorization(timestamp);
            //var sign = this.GetSign(timestamp);
            //// /Accounts/{accountSid}/{func}/{funcdes}?sig={SigParameter}
            //var url = string.Format("{0}/Accounts/{1}/{func}/{funcdes}?sig={2}", this.BaseUrl, this.AccountId, sign);
            //var result = HttpHelper.Send(url, "POST", "", new HttpConfig(authorization));
            string ret = null;

            CCPRestSDK.CCPRestSDK api = new CCPRestSDK.CCPRestSDK();
            //ip格式如下，不带https://
            bool isInit = api.init("app.cloopen.com", "8883");
            api.setAccount(this.AccountId, this.Token);
            api.setAppId(this.AppId);

            try
            {
                if (isInit)
                {
                    Dictionary<string, object> retData = api.SendTemplateSMS(phone, tempateId, data);
                    ret = getDictionaryData(retData);
                }
                else
                {
                    ret = "初始化失败";
                }
            }
            catch (Exception exc)
            {
                //ret = exc.Message;
                ret = "请求失败";
            }

            return ret;
        }
        #endregion

        #region 公有方法

        /// <summary>
        /// 随机生成验证码
        /// </summary>
        public string RandomValidCode()
        {
            return new Random().Next(1000, 9999).ToString();
        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        public string SendValidCode(string phone, string validcode)
        {
            var data = new string[] { string.Format(this.Message, validcode, "10") };
            return this.Send(phone, this.TemplateId, data);
        }

        public string SendModifyPassord(string phone, string password)
        {

            var data = new string[] { password };
            return this.Send(phone, this.RandomPasswordTemplateId, data);
        }

        /// <summary>
        /// 发送订单消息
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="siteName"></param>
        /// <param name="orderDate"></param>
        /// <returns></returns>
        public string SendSiteOrderInfo(string phone, string siteName, DateTime orderDate) {
            var data = new string[] { siteName, orderDate.ToString("yyyy_MM-dd HH:ss") };
            return this.Send(phone, this.SiteOrderTemplateId, data);
        }

        /// <summary>
        /// 发送场地推荐消息
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string SendSiteFlowInfo(string phone,string[] data)
        {
            return this.Send(phone, this.SiteFlowTemplateId, data);
        }

        /// <summary>
        /// 发送订单指派消息
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string SendGiveOrderInfo(string phone,string[] data)
        {
            return this.Send(phone, this.GiveOrderTemplateId, data);
        }

        /// <summary>
        /// 申请审核消息
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string SendApplyInfo(string phone, string[] data)
        {
            return this.Send(phone, this.ApplyTemplateId, data);
        }

        /// <summary>
        /// 审核回复消息
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string SendAuditingInfo(string phone, string[] data)
        {
            return this.Send(phone, this.AuditingTemplateId, data);
        }

        /// <summary>
        /// 发送小程序信息
        /// </summary>
        public string SendWeChatInfo(string phone, string[] data)
        {
            return this.Send(phone, this.WeChatTemplateId, data);
        }

        /// <summary>
        /// 需求单超期提醒
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string SendCheckOrderInfo(string phone,string[] data)
        {
            return this.Send(phone, this.CheckOrderTemplateId, data);
        }

        /// <summary>
        /// 登录验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string SendCode(string phone, string[] data)
        {
            return this.Send(phone, this.Code, data);
        }

        /// <summary>
        /// 注册验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string SendRegisterCode(string phone, string[] data)
        {
            return this.Send(phone, this.RegisterCode, data);
        }
        #endregion


    }
}
